package com.jeeplus.modules.api.utils;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:58<br>
 * 描述: ApiUserUtils <br>
 */
public class ApiUserUtils {
	private static final Logger logger = LoggerFactory.getLogger(Tool.class);

	private static final String getCode = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s&state=STAT#wechat_redirect";
	private static final String webAccessTokenhttps = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";
	private static final String userMessage = "https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN";




    //替换字符串
    public static String getCode(String APPID, String REDIRECT_URI, String SCOPE) {
        return String.format(getCode, APPID, REDIRECT_URI, SCOPE);
    }

	//替换字符串
	public static String getWebAccess(String CODE, String appId, String secret) {
		return String.format(webAccessTokenhttps,
				appId,
				secret,
				CODE);
	}

    //替换字符串
    public static String getUserMessage(String access_token, String openid) {
        return String.format(userMessage, access_token, openid);
    }
    
    /**
     * 获取AccessToken
     * @param appid
     * @param appsecret
     * @return
     */
	public static AccessToken getAccessToken(String appid, String appsecret) {
		AccessToken accessToken = null;
		String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"
				.replace("APPID", appid).replace("APPSECRET", appsecret);
		JSONObject jsonObject = CommonUtil.httpsRequest(requestUrl, "GET", null);
		if (jsonObject != null) {
			try {
				accessToken = new AccessToken();
				accessToken.setToken(jsonObject.getString("access_token"));
				accessToken.setExpiresIn(jsonObject.getInteger("expires_in"));
			} catch (JSONException e) {
				logger.error("获取token失败 errcode:{} errmsg:{}" + jsonObject.getInteger("errcode")
						+ jsonObject.getString("errmsg"));
				e.printStackTrace();
			}
		}
		return accessToken;
	}
}